import React, { memo } from 'react';
import { Form } from 'antd';
import type { FormItemProps as AntFormItemProps } from 'antd';
import classNames from 'classnames';
import styles from './FormItem.module.css';

/**
 * 表单项组件属性接口
 * @description 扩展 Ant Design Form.Item 组件的属性
 */
export interface IFormItemProps extends AntFormItemProps {
  /** 是否必填 */
  required?: boolean;
  /** 是否显示必填标记 */
  showRequiredMark?: boolean;
  /** 标签提示信息 */
  labelTooltip?: string | React.ReactNode;
  /** 字段描述信息 */
  description?: string | React.ReactNode;
  /** 是否禁用该字段 */
  disabled?: boolean;
  /** 是否只读 */
  readonly?: boolean;
  /** 字段尺寸 */
  size?: 'small' | 'middle' | 'large';
  /** 自定义类名 */
  className?: string;
  /** 子元素 */
  children?: React.ReactNode;
}

/**
 * 表单项组件
 * @description 基于 Ant Design Form.Item 的自定义表单项，提供统一的样式和行为
 */
const FormItem = memo<IFormItemProps>(({
  required = false,
  showRequiredMark = true,
  labelTooltip,
  description,
  disabled = false,
  readonly = false,
  size = 'middle',
  className,
  children,
  rules,
  ...props
}) => {
  // 处理验证规则
  const getValidationRules = () => {
    const validationRules = [...(rules || [])];

    // 如果设置了必填，添加必填验证规则
    if (required) {
      const requiredRule = {
        required: true,
        message: `请输入${props.label || '该字段'}`
      };

      // 检查是否已经有必填规则
      const hasRequiredRule = validationRules.some(rule => 
        typeof rule === 'object' && rule !== null && 'required' in rule
      );

      if (!hasRequiredRule) {
        validationRules.unshift(requiredRule);
      }
    }

    return validationRules;
  };

  // 处理标签显示
  const getLabel = () => {
    if (!props.label) {
      return undefined;
    }

    const labelContent = (
      <span className={styles.labelContent}>
        {props.label}
        {labelTooltip && (
          <span className={styles.labelTooltip} title={typeof labelTooltip === 'string' ? labelTooltip : undefined}>
            {typeof labelTooltip === 'string' ? ' ?' : labelTooltip}
          </span>
        )}
      </span>
    );

    return labelContent;
  };

  // 处理帮助信息
  const getExtra = () => {
    if (description) {
      return (
        <div className={styles.description}>
          {description}
        </div>
      );
    }
    return props.extra;
  };

  // 克隆子元素并添加属性
  const renderChildren = () => {
    if (!children) {
      return children;
    }

    return React.Children.map(children, (child) => {
      if (React.isValidElement(child)) {
        const childProps: any = {};

        // 传递禁用状态
        if (disabled) {
          childProps.disabled = true;
        }

        // 传递只读状态
        if (readonly) {
          childProps.readOnly = true;
        }

        // 传递尺寸
        if (size && !child.props.size) {
          childProps.size = size;
        }

        // 如果有新属性需要传递，克隆元素
        if (Object.keys(childProps).length > 0) {
          return React.cloneElement(child, {
            ...childProps,
            ...child.props, // 保持原有属性优先级
          });
        }
      }

      return child;
    });
  };

  // 组合类名
  const formItemClassName = classNames(
    styles.formItem,
    {
      [styles.required]: required && showRequiredMark,
      [styles.disabled]: disabled,
      [styles.readonly]: readonly,
      [styles.small]: size === 'small',
      [styles.large]: size === 'large',
      [styles.hasTooltip]: !!labelTooltip,
      [styles.hasDescription]: !!description,
    },
    className
  );

  return (
    <Form.Item
      {...props}
      label={getLabel()}
      extra={getExtra()}
      rules={getValidationRules()}
      required={required && showRequiredMark}
      className={formItemClassName}
    >
      {renderChildren()}
    </Form.Item>
  );
});

FormItem.displayName = 'FormItem';

export default FormItem;